﻿#include"alg.h"
#include<string.h>


int set_value(chanel_t* pchnl, uint32_t val)
{
	if (!pchnl)return -1;
	int32_t dtv1 = (val - pchnl->last) /* / pchnl->last*/;
	pchnl->last = val;

	int32_t dtv2 = (dtv1 - pchnl->lastdtv1) /*/ pchnl->lastdtv1*/;

	pchnl->lastdtv1 = dtv1;
	pchnl->dtv1[pchnl->idx] = dtv1;
	pchnl->idx++;
	if (pchnl->idx >= MAX_COUNTS)
	{
		pchnl->idx = 0;
		if (pchnl->flag)
        {
            for (int i = 0; i < MAX_COUNTS; i++)
            {
                fprintf(pchnl->m_file, "%d,", pchnl->dtv1[i]);
            }
            fprintf(pchnl->m_file, "\n");
            fflush(pchnl->m_file);
        }
    }

	pchnl->dtv2[pchnl->idx2] = dtv2;
	pchnl->idx2++;
	if (pchnl->idx2 >= MAX_COUNTS)
	{
		if (pchnl->flag)
		{
			fprintf(pchnl->m_file, "----------");
			for (int i = 0; i < MAX_COUNTS; i++)
			{
				fprintf(pchnl->m_file, "%d,", pchnl->dtv1[i]);
			}
			fprintf(pchnl->m_file, "\n");
			fflush(pchnl->m_file);
		}
		pchnl->idx2 = 0;
	}
	return 0;
}

void init_chanel(chanel_t* pchnl)
{
	if (!pchnl)return;
	pchnl->avg = 0;
	pchnl->base = 0;
	pchnl->col = 0;
	pchnl->idx = 0;
	pchnl->idx2 = 0;
	pchnl->max = 0;
	pchnl->min = 0xffff - 1;
	pchnl->row = 0;
	pchnl->m_file = NULL;
	memset(pchnl->dtv1, 0x00, sizeof(pchnl->dtv1));
	memset(pchnl->dtv2, 0x00, sizeof(pchnl->dtv2));
	pchnl->flag = false;
}

void set_save(chanel_t* pchnl, bool flag)
{
	if (flag)
	{
		if (!pchnl->m_file)
		{
			char buf[32] = { 0 };
			sprintf(buf, "chanel-%d.csv", pchnl->num);
			pchnl->m_file = fopen(buf, "w");
		}
		else
		{
			fclose(pchnl->m_file);
			char buf[32] = { 0 };
			sprintf(buf, "chanel-%d.csv", pchnl->num);
			pchnl->m_file = fopen(buf, "w");
		}
	}
	else
	{
		if (pchnl->m_file)
		{
			fclose(pchnl->m_file);
		}
	}
	pchnl->flag = flag;
}
